<template>
  <div class="app-container">
    <div class="filter-container">
      <!-- <el-input v-model="listQuery.name$lk" placeholder="姓名" clearable class="filter-item" /> -->
      <el-select v-model="listQuery.status" placeholder="类型" clearable class="filter-item">
        <el-option v-for="item in statusJson" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter"
        >
        查询
      </el-button>
      <el-button class="filter-item" type="warning" icon="el-icon-sort" @click="handlePlRead">
        批量已读
      </el-button>
      <el-button class="filter-item" type="danger" icon="el-icon-delete" @click="handlePlDelete"
        >
        批量删除
      </el-button>
    </div>
    <el-table v-loading="listLoading" :data="list" border fit highlight-current-row row-key="id" style="width: 100%;"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="40" />
      <el-table-column label="序号" type="index" align="center" width="60px" />
      <el-table-column label="内容" prop="content" align="center" />
      <el-table-column label="类型" prop="typeText" align="center" />
      <el-table-column label="状态" prop="statusText" align="center" />
      <el-table-column label="创建时间" prop="createTime" align="center" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button size="mini" @click="handleDetail(row)">
            查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageSize"
      @pagination="getList" />

  </div>
</template>

<script>
import { messagePageByQo, messageRemoveByIds, messageRead, messageCheck } from '@/api/system'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination'
import { messageTypeJson } from './constant'
export default {
  name: 'MessageManager',
  directives: { waves },
  components: { Pagination },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        pageNo: 1,
        pageSize: 20,
        name$lk: '',
        status: '',
      },
      multipleSelection: [],
      statusJson: [
        { value: 0, label: '未读' },
        { value: 1, label: '已读' }
      ],
      messageTypeJson
    }
  },
  created() {
    this.getList()
    // this.$store.dispatch('user/getMessageCount')
  },
  methods: {
    getList() {
      this.listLoading = true
      messagePageByQo(this.listQuery).then(response => {
        this.list = response.list || []
        this.total = response.totalCount
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    // 批量操作
    handleSelectionChange(val) {
      this.multipleSelection = val.map((ele) => {
        return ele.id
      })
    },
    handlePlDelete() {
      if (!this.multipleSelection || this.multipleSelection.length < 1) {
        this.$message.error('请至少选择一条数据')
        return
      }
      const params = {
        ids: this.multipleSelection.join(',')
      }
      this.$confirm('是否继续删除？').then(() => {
        messageRemoveByIds(params).then(() => {
          // this.$notify({
          //   title: '成功',
          //   message: '批量删除成功！',
          //   type: 'success',
          //   duration: 2000
          // })

          this.$message({
            message: '批量删除成功！',
            type: 'success'
          });
          this.getList()
          this.$store.dispatch('user/getMessageCount')
        })
      })
    },
    handlePlRead() {
      if (!this.multipleSelection || this.multipleSelection.length < 1) {
        this.$message.error('请至少选择一条数据')
        return
      }
      const params = {
        ids: this.multipleSelection.join(',')
      }
      this.$confirm('是否继续操作？').then(() => {
        messageRead(params).then(() => {
          // this.$notify({
          //   title: '成功',
          //   message: '操作成功！',
          //   type: 'success',
          //   duration: 2000
          // })

          this.$message({
            message: '操作成功！',
            type: 'success'
          });
          this.getList()
          this.$store.dispatch('user/getMessageCount')
        })
      })
    },
    handleDetail(row) {
      let findItem = ''
       this.messageTypeJson.some(item => {
        if (item.value === row.type) {
          if (item.value === 923) { //集采交易-已完成 ——发布人（供应商）和报名人（采购商）
            let userInfo = Object.assign({}, this.$store.getters.userInfo);
            if (userInfo.type === 1) {//采购商
              findItem = { value: 923, label: "集采交易-已完成", path:'/transaction/groupReg', status: "1"};
            } else {//供应商
              findItem = { value: 923, label: "集采交易-已完成", path:'/transaction/groupBuying', status: "1"};
            }
          } else {
            findItem = item
          }
          
          return true
        }
      });

      if (row.content.includes("：")) {
        var identifier = row.content.split("：")[1];
        messageCheck({"identifier" : identifier, "type" : row.type}).then(response => {
          if (response.length > 0) {
            findItem.status = response[0].status
          } else {
            findItem.status = "";
          }
          this.toDetail(row.id, findItem, identifier)
        }).catch(error => {
          console.log(error);
        })
      }
    },
    toDetail(id, findItem, identifier) {
      this.readMessage(id).then(res => {
        if (findItem) {
          this.$store.dispatch('user/getMessageCount')
          this.$router.push({ path: findItem.path, query: {identifier:identifier, status: findItem.status, t: Date.now()} })
        } else {
          this.$message.error('未找到相关信息')
        }
      })
    },
    readMessage(id) {
      return new Promise((resolve, reject) => {
        messageRead({ ids: id })
          .then(res => {
            resolve(res);
          })
          .catch(err => {
            reject(err);
          });
      });
    },
  }
}
</script>
